import React from 'react';
import { Form, Radio, InputNumber, Input, Row, Col, Button, message, Modal } from 'antd';
import { history } from 'umi'

import { DEPARTMENT_SUGGEST_TYPE, DEPARTMENT_SUGGEST_TYPE_ENUM } from '@/pages/Recruitment/dictionary';
import { saveDepartCommunicate } from '@/pages/Recruitment/service';
import { useRequest, defaultFormatResult } from '@/hooks';
import { SalaryYearInput, SalaryMonthInput } from '@/pages/Recruitment/components/SalaryInput';
// import { formatToThreePart } from '@/utils/utils';
import pageTabUtil from '@/utils/pageTabUtil';
import useSalaryChange from '../../hooks/useSalaryChange';
import { DiffSalary } from './index';
import styles from '../index.less';

const { TextArea } = Input;

const formLayout = { labelAlign: 'right', labelCol: { span: 3 }, wrapperCol: { span: 14 } };
const inlineLayout = { labelAlign: 'right', labelCol: { span: 4 }, wrapperCol: { span: 14 } };

const DepartmentSuggest = ({ form, communicateCode, talentInfo, commInfo, oneLineLayout, candidateId }) => {
    const { getFieldDecorator, validateFieldsAndScroll } = form;
    const handleChangeSalary = useSalaryChange(form);

    const [showDiff, setShowDiff] = React.useState(false);
    const ref = React.useRef();

    // 沟通提交
    const { loading: submitLoading, run: runSubmit } = useRequest(saveDepartCommunicate, {
        manual: true,
        ...defaultFormatResult
    });

    const childProps = {
        form,
        commInfo,
        talentInfo,
        oneLineLayout
    };

    const handleSubmit = () => {
        validateFieldsAndScroll(
            {
                scroll: {
                    offsetBottom: 88
                }
            },
            async (errors, values) => {
                if (!errors) {
                    const payload = {
                        ...values
                    };
                    const result = await runSubmit(communicateCode, payload);
                    if (result) {
                        message.success('提交成功！');
                        // history.go(-1);
                        history.push({
                            pathname: '/office/personnelManagement/recruitment/hire/detail',
                            query: {
                                candidateId,
                                employId: commInfo.employId
                            },
                            state: {
                                tabRoute: true,
                                tabRefresh: true,
                                closeTab: true
                            }
                        });
                    }
                }
            }
        );
    };

    const handleShowDiff = e => {
        e.preventDefault();
        setShowDiff(true);
    };

    const currentSuggestedMonthSalary = form.getFieldValue('suggestedMonthSalary');

    React.useEffect(() => {
        if (!currentSuggestedMonthSalary) return;
        form.setFieldsValue({ fractional: ref.current?.getPercent() });
    }, [currentSuggestedMonthSalary]);

    const currentSuggestedStatus = form.getFieldValue('suggestedStatus');
    const isOut = currentSuggestedStatus === DEPARTMENT_SUGGEST_TYPE_ENUM.OUT;

    const renderContent = () => {
        if (isOut) {
            return (
                <Form.Item label="理由" {...formLayout}>
                    {getFieldDecorator('remark', {
                        initialValue: '',
                        rules: [
                            {
                                required: true,
                                message: '理由不能为空'
                            },
                            {
                                max: 500,
                                message: '理由不能超过500个字符'
                            }
                        ]
                    })(<TextArea placeholder="请输入理由" style={{ height: 100 }} />)}
                </Form.Item>
            );
        }
        return (
            <>
                <Row>
                    <Col span={12}>
                        <Form.Item label="建议年薪" {...{ ...inlineLayout, labelCol: { span: 6 } }}>
                            <div style={{ display: 'flex' }}>
                                {getFieldDecorator('suggestedYearSalary', {
                                    // initialValue: commInfo?.recruitSalaryRecordVO?.suggestedYearSalary,
                                    rules: [
                                        {
                                            required: true,
                                            message: '建议年薪不能为空'
                                        }
                                    ]
                                })(
                                    <InputNumber
                                        // formatter={formatToThreePart}
                                        min={0}
                                        placeholder="请输入建议年薪"
                                        style={{ width: '60%' }}
                                        onChange={value => {
                                            handleChangeSalary('suggestedYearSalary', value);
                                        }}
                                        formatter={val => SalaryYearInput(val, true)}
                                        parser={val => SalaryYearInput(val)}
                                    />
                                )}
                                <span style={{ marginLeft: 8 }}>
                                    {talentInfo?.employSalaryCurrencyCode || talentInfo?.companyCurrencyCode}
                                </span>
                            </div>
                        </Form.Item>
                    </Col>
                    <Col span={11}>
                        <Form.Item label="建议月薪" {...inlineLayout}>
                            <div className={styles.formLineWrap}>
                                <Form.Item>
                                    {getFieldDecorator('suggestedMonthSalary', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '建议月薪不能为空'
                                            }
                                        ]
                                    })(
                                        <InputNumber
                                            style={{ width: '100%' }}
                                            // formatter={formatToThreePart}
                                            placeholder="请输入建议月薪"
                                            onChange={value => {
                                                handleChangeSalary('suggestedMonthSalary', value);
                                            }}
                                            formatter={val => SalaryMonthInput(val, true)}
                                            parser={val => SalaryMonthInput(val)}
                                        />
                                    )}
                                </Form.Item>
                                <span style={{ padding: '0 5px' }}>X</span>
                                <Form.Item>
                                    {getFieldDecorator('suggestedMonthNumber', {
                                        initialValue: commInfo?.recruitSalaryRecordVO?.suggestedMonthNumber || 16,
                                        rules: [
                                            {
                                                required: true,
                                                message: '月份不能为空'
                                            }
                                        ]
                                    })(
                                        <InputNumber
                                            min={12}
                                            onChange={value => {
                                                handleChangeSalary('suggestedMonthNumber', value);
                                            }}
                                        />
                                    )}
                                </Form.Item>
                                <span style={{ marginLeft: 8 }}>
                                    {talentInfo?.employSalaryCurrencyCode || talentInfo?.companyCurrencyCode || '月'}
                                </span>
                            </div>
                        </Form.Item>
                    </Col>
                </Row>
                <Form.Item label="分位数" {...formLayout}>
                    {getFieldDecorator('fractional')(
                        <Input style={{ width: '304px', marginRight: '12px' }} disabled placeholder="自动生成" />
                    )}
                    <a href="#" onClick={handleShowDiff}>
                        查看薪资对比
                    </a>
                </Form.Item>
                <Form.Item label="说明" {...formLayout}>
                    {getFieldDecorator('remark', {
                        initialValue: '',
                        rules: [
                            { required: true, message: '理由不能为空' },
                            { max: 500, message: '理由不能超过500个字符' }
                        ]
                    })(<TextArea placeholder="请输入理由" style={{ height: 100 }} />)}
                </Form.Item>
            </>
        );
    };
    return (
        <>
            <Form style={{ paddingTop: '16px' }}>
                <Form.Item label="用人部门建议" {...formLayout}>
                    {getFieldDecorator('suggestedStatus', {
                        // initialValue: DEPARTMENT_SUGGEST_TYPE[0].value,
                        initialValue: null,
                        rules: [{ required: true, message: '必须选择建议' }]
                    })(
                        <Radio.Group>
                            {DEPARTMENT_SUGGEST_TYPE.map(item => (
                                <Radio value={item.value} key={item.value}>
                                    {item.text}
                                </Radio>
                            ))}
                        </Radio.Group>
                    )}
                </Form.Item>
                {renderContent()}
            </Form>
            <div className={styles.buttonWrapper}>
                <Button
                    onClick={() => {
                        pageTabUtil.goBack();
                    }}
                >
                    取消
                </Button>
                <Button loading={submitLoading} onClick={handleSubmit} type="primary" style={{ marginLeft: 12 }}>
                    确定
                </Button>
            </div>
            <Modal
                title="薪资对比"
                forceRender
                visible={showDiff}
                onOk={() => setShowDiff(false)}
                onCancel={() => setShowDiff(false)}
                width={750}
            >
                <DiffSalary {...childProps} ref={ref} />
            </Modal>
        </>
    );
};

export default Form.create()(DepartmentSuggest);
